import { Box, Typography } from '@mui/material';
import { Button, Col, Divider, Form, Input, Row, Select } from 'antd';
import { SketchPicker } from 'react-color';
import { useEffect, useState } from 'react';
import { CMEVENTS, QueryParamKeys, getQueryParam, http } from '@amcax/base';
import { getAirfoilVertexes } from '../../../../commands/cmd-airfoil/cmdAirfoilAPI';
import './closeButton.scss';
import { userEvents } from '../../../../../../module';

type FormDataLike = {
  alpha_start: number;
  alpha_end: number;
  step: number;
  reynolds_number: number;
};

export const clearLocalListDatas = () => {
  localStorage.removeItem('task_id');
  localStorage.removeItem('task_result');
  localStorage.removeItem('color');
  localStorage.removeItem('formData');
};

const docID = getQueryParam<string>(QueryParamKeys.DOCUMENT_ID);
export default function InputPanel() {
  const width = 300;
  const [color, setColor] = useState('#ffff00');
  const [displayColorPicker, setdDisplayColorPicker] = useState(false);
  const [noInput, setNoInput] = useState(false);
  const [noSubmit, setNoSubmit] = useState(false);
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState<FormDataLike>({
    alpha_start: 5.0,
    alpha_end: 10.0,
    step: 1.0,
    reynolds_number: 5000000,
  });

  useEffect(() => {
    // 判断是否已有任务存在
    const localFormData = localStorage.getItem('formData');
    if (localFormData) {
      setFormData(JSON.parse(localFormData));
    }
    const localColor = localStorage.getItem('color');
    if (localColor) {
      setColor(localColor);
    }
    const task_id = localStorage.getItem('task_id');
    if (task_id) {
      setLoading(true);
      setNoInput(true);
    }
    const task_result = localStorage.getItem('task_result');
    if (task_result) {
      setNoSubmit(true);
    }
  }, []);

  /**修改下拉参数 */
  const handleSelectChange = (value) => {
    setNoSubmit(false);
    if (typeof value === 'string' && !isNaN(Number(value))) {
      value = Number(value);
    }
    setFormData((prevState) => ({
      ...prevState,
      ['step']: value,
    }));
  };

  /**修改表单参数 */
  const handleFormDataChange = (event) => {
    setNoSubmit(false);
    let { name, value } = event.target;
    setFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  /**校验表单参数 */
  const checkAirformData = (minValue, maxValue) => (event) => {
    setNoSubmit(false);
    let { name, value, type } = event.target;
    if (type === 'number') value = Number(value);
    if (isNaN(value)) {
      return;
    }
    if (value < minValue) {
      value = minValue;
    } else if (value > maxValue) {
      value = maxValue;
    }
    const nearestMultiple = Math.round(value / formData.step) * formData.step;
    value = nearestMultiple;
    setFormData((prevState) => ({
      ...prevState,
      [name]: value.toFixed(2),
    }));
  };

  const handleColorChange = (newColor) => {
    setColor(newColor.hex);
    setNoSubmit(false);
  };

  const openColorCard = () => {
    setdDisplayColorPicker(true);
  };

  const closeColorCard = () => {
    setdDisplayColorPicker(false);
  };

  const handleSubmit = async () => {
    const vertexes = await getAirfoilVertexes();
    const params = {
      alpha_start: Number(formData.alpha_start),
      alpha_end: Number(formData.alpha_end),
      step: Number(formData.step),
      reynolds_number: [formData.reynolds_number],
      data: vertexes,
    };
    const taskCreateAddr = `/airfoil/v1/${docID}/cfd/task/create`;
    await http.post(taskCreateAddr, params).then(async (res) => {
      const taskID_JSON = JSON.stringify(res.data.task_id);
      const taskID = JSON.parse(taskID_JSON);
      setLoading(true);
      setNoInput(true);
      clearLocalListDatas();
      localStorage.setItem('color', color);
      localStorage.setItem('formData', JSON.stringify(formData));
      localStorage.setItem('task_id', JSON.stringify(taskID));
      checkTask(taskID);
    });
  };

  // 查询任务状态
  const checkTask = async (taskID) => {
    const data = {
      task_id: taskID,
    };
    const taskCheckAddr = `/airfoil/v1/${docID}/cfd/task/query`;
    const interval = setInterval(() => {
      http.post(taskCheckAddr, data).then(async (res) => {
        const task_status = JSON.stringify(res.data.task_status);
        if (task_status === '2') {
          // 任务已完成
          clearInterval(interval);
          setLoading(false);
          setNoInput(false);
          setNoSubmit(false);
          localStorage.removeItem('task_id');
          localStorage.setItem(
            'task_result',
            JSON.stringify(res.data.task_result),
          );
          localStorage.setItem('color', color);
          localStorage.setItem('formData', JSON.stringify(formData));
          userEvents.emit(CMEVENTS.WIDGET_RIGHT_NAV_SHOW, {
            show: true,
            id: 'result',
          });
        } else if (task_status !== '2' && task_status !== '1') {
          // 任务失败
          setLoading(false);
          setNoInput(false);
          setNoSubmit(false);
          clearLocalListDatas();
          clearInterval(interval);
        }
      });
    }, 15000);
  };

  return (
    <Box sx={{ p: '20px', width: width + 'px' }}>
      <div style={{ display: 'flex' }}>
        <Typography component='h4'>数据输入</Typography>
        <button
          style={{ marginLeft: 'auto' }}
          className='close-button'
          onClick={() => {
            userEvents.emit(CMEVENTS.RIGHT_NAV_ITEM_CLICK, {
              id: 'input',
            });
            userEvents.emit(CMEVENTS.WIDGET_RIGHT_NAV_SHOW, {
              show: false,
              id: 'input',
            });
          }}>
          ×
        </button>
      </div>
      <Box
        sx={{
          mt: '10px',
          overflowY: 'auto',
          width: '100%',
          height: '100%',
        }}>
        <div style={{ padding: '10px' }}>
          <Form layout='vertical'>
            {/* Alpha α 分析 */}
            <Form.Item>
              <Divider orientation='left'>Alpha α 分析</Divider>
              <Row gutter={16}>
                <Col style={{ display: 'flex', flexDirection: 'column' }}>
                  <Form.Item label='降低 α alpha'>
                    <Input
                      type='number'
                      name='alpha_start'
                      value={
                        typeof formData.alpha_start === 'number'
                          ? formData.alpha_start.toFixed(2)
                          : formData.alpha_start
                      }
                      step={1.0}
                      min={-8.0}
                      max={13.0}
                      disabled={noInput}
                      onChange={handleFormDataChange}
                      onBlur={checkAirformData(-8.0, 13.0)}
                    />
                  </Form.Item>
                </Col>
                <Col style={{ display: 'flex', flexDirection: 'column' }}>
                  <Form.Item label='升高 α alpha'>
                    <Input
                      type='number'
                      name='alpha_end'
                      value={
                        typeof formData.alpha_end === 'number'
                          ? formData.alpha_end.toFixed(2)
                          : formData.alpha_end
                      }
                      step={1.0}
                      min={-8.0}
                      max={13.0}
                      disabled={noInput}
                      onChange={handleFormDataChange}
                      onBlur={checkAirformData(-8.0, 13.0)}
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label='步进'>
                    <Select
                      ref={null}
                      disabled={noInput}
                      value={formData.step?.toFixed(2)}
                      onChange={(value) => handleSelectChange(value)}
                      options={[
                        { value: (0.5).toFixed(2) },
                        { value: (1.0).toFixed(2) },
                      ]}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form.Item>

            {/* 分析雷诺数 */}
            <Form.Item>
              <Divider orientation='left'>分析雷诺数</Divider>
              <Row
                align='middle'
                gutter={16}>
                <Col>
                  <Form.Item noStyle>
                    <Input
                      type='number'
                      name='reynolds_number'
                      value={formData.reynolds_number}
                      disabled={true}
                      onChange={handleFormDataChange}
                    />
                  </Form.Item>
                </Col>
                {/* <Col>
                    <Checkbox defaultChecked />
                  </Col> */}
                <Col>
                  <div
                    onClick={() => {
                      if (!noInput) {
                        openColorCard();
                      }
                    }}
                    style={{
                      width: 24,
                      height: 24,
                      backgroundColor: color,
                      border: '1px solid #ddd',
                      cursor: 'pointer',
                    }}
                  />
                </Col>
              </Row>
            </Form.Item>
          </Form>
          {displayColorPicker ? (
            <div style={{ position: 'absolute', zIndex: 2 }}>
              <div
                style={{
                  position: 'fixed',
                  top: 0,
                  right: 0,
                  bottom: 0,
                  left: 0,
                }}
                onClick={closeColorCard}
              />
              <SketchPicker
                color={color}
                onChange={handleColorChange}
              />
            </div>
          ) : null}
        </div>
        <div
          style={{
            justifyContent: 'left',
            display: 'flex',
          }}>
          {loading ? (
            <Button
              type='primary'
              style={{ borderRadius: '5px' }}
              loading={loading}
              onClick={handleSubmit}>
              {'任务进行中'}
            </Button>
          ) : (
            <Button
              type='primary'
              style={{ borderRadius: '5px' }}
              disabled={noSubmit}
              onClick={handleSubmit}>
              {'提交任务'}
            </Button>
          )}
        </div>
      </Box>
    </Box>
  );
}
